<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Home extends MY_Controller {

	/**
	 * 产品模型
	 * @var ConsumerProductModel
	 */
	public $mProduct;
	
	/**
	 * 商户模型
	 * @var MerchantUserModel
	 */
	public $mMerchant;
	
	/**
	 * 产品评论模型
	 * @var MerchantCommentModel
	 */
	public $mComment;
	
	public function __construct(){
		parent::__construct();	
		$this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
		$this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
		$this->loadModel('MerchantCommentModel', 'mComment', 'merchant');
	}
	
	//////////////////////////////////////////////////////////////////
	//+--------------------------------------------------------------
	//|	商品
	//+--------------------------------------------------------------
	/**
	 * 首页
	 */
	public function index(){

		$data = array(
				'status'=> $this->mProduct->getStatus(),
				'title'=>'商品管理',
		);
		
		$this->view('product/home/home', $data, 'datatable,select2,validation,datepicker');
	}
	
	/**
	 * 首页
	 */
	public function details(){
		$id = get('id');
		$tProduct = $this->mProduct->getInfo($id);
		if (! $tProduct){
			show_404();
		}

		$this->loadModel('ConsumerCategoryModel', 'mCategory', 'consumer');
		$data = array(
		        'backUrl' => getUrl('product/home'),
				'title'=>'商品详情',
				'info'=>$tProduct,
				'merchant'=>$this->mMerchant->getInfo($tProduct['merchant_id']),
				'category'=>$this->mCategory->getCustomInfo($tProduct['category_id']),
		);
		$this->view('product/home/details', $data, 'datatable,select2,validation,datepicker,uniform');
	}
	
	
	/**
	 * 添加
	 */
	public function add(){
		
		$data = array(
				'title'=>'新增商品',
				'add'=>1,
                'changeMerchant' => true,
            'backUrl' => getUrl('product/home'),
		);
		
		$this->view('product/home/form', $data, 'fileinput,uniform,webuploader,datatable,select2,validation,dropify,cropit_master');
	}
	
	/**
	 * 编辑
	 */
	public function edit(){
		$id = get('id');
		$tProduct = $this->mProduct->getInfo($id);
		if (! $tProduct){
			show_404();
		}
		$this->loadModel('ConsumerCategoryModel', 'mCategory', 'consumer');
		
		//获取商家信息
		$tMerchant = $this->mMerchant->getInfo($tProduct['merchant_id']);
		//获取商家分类
		$tCategory = $this->mCategory->getCustomList($tProduct['merchant_id']);
		//获取产品规格
		$tProperty = $this->mProduct->getPropertyList($id);
		//获取产品详情
		$tDetail  = $this->mProduct->getDetailList($id);
        //获取产品属性
        $tags = $this->mProduct->getTagsList($id);

		$data = array(
            'title'=>'编辑商品',
            'info'=>$tProduct,
            'merchant'=>$tMerchant,
            'category'=>$tCategory,
            'property'=>$tProperty,
            'tags'=>$tags,
            'detail'=>$tDetail,
            'add'=>0,
            'changeMerchant' => true,
            'backUrl' => getUrl('product/home'),
		);

		$this->view('product/home/form', $data, 'fileinput,uniform,webuploader,datatable,select2,validation,dropify,cropit_master');
	}

    /**
     * 保存
     */
	public function save(){
		//表单验证
		$vConf = array(
            array('name', '商品名称', 'required'),
            array('goods_price', '商品价格', 'required'),
            array('lunch_box_fee', '打包费', 'required'),
            array('is_limited', '库存设置', 'required|is_natural_no_zero'),
            array('quantity', '库存数量', 'required'),
//            array('weight', '商品重量', 'required|is_numeric'),
//            array('is_free_shipping', '是否包邮', 'required|in_list[1,2]'),
            array('category_id', '分类id', 'required|is_natural_no_zero'),
            array('merchant_id', '商家id', 'required|is_natural_no_zero'),
            array('status', '状态', 'required|in_list[0,1,2]'),
// 				array('lable[]', '标签', 'required'),
				
		);
		$this->formDataValidation($vConf);
	
		//参数
		$id 			= (int)post('id');
		$name 			= trim(post('name'));
		$goods_price 	= trim(post('goods_price'));
		$lunch_box_fee 	= trim(post('lunch_box_fee')); // 打包费
		$is_limited 	= trim(post('is_limited'));
		$quantity 		= trim(post('quantity'));
		$weight 	    =  trim(post('weight'));
		$category_id	= trim(post('category_id'));
		$merchant_id 	= trim(post('merchant_id'));
		$status 		= trim((int)post('status'));
		$is_free_shipping 		= 1; // trim((int)post('is_free_shipping'));

		$lable 			= post('lable');
		$tag 			= post('tag'); // 属性

		$detail			= post('detail');
		$imgs 			= post('imgs');//编辑时 提交的旧图片
	
		$images 		= post('img');
        $icon = trim(post('icon'));

		if ( ! $id ){
			//增加
			if (!$icon){
				$this->ajaxReturn(0,'未上传封面图');
			}
		}
		if($images && count($images) > 3){
		    $this->ajaxReturn(0,'轮播图最多三张');
        }
		//数据
		$data = array(
				'merchant_id'=>$merchant_id,
				'name'=>$name,
				'goods_price'=>$goods_price,
				'lunch_box_fee'=>$lunch_box_fee,
				'is_limited'=>$is_limited,
				'quantity'=>$quantity,
				'weight'=>$weight,
				'status'=>$status,
				'is_free_shipping'=>$is_free_shipping,
				'category_id'=>$category_id,
		);

		//开启事务
		$this->db->trans_begin();
		
		if ($id){
			//修改
			$query = $this->mProduct->save($data,$id);
			if (! $query){
				$this->db->trans_rollback();
				$this->ajaxReturn(0,'保存失败');
			}
		}else{
			//新增
			$data['addtime'] = time();
			$data['sale_quantity'] = 0;
			
			$tId = $this->mProduct->save($data);
			if (! $tId){
				$this->db->trans_rollback();
				$this->ajaxReturn(0,'保存失败');
			}
		}
		
		$tId = $id ?: $tId;
		
		/**
		 * 标签重置
		 */
		if ( ! empty($lable[0]['lable'])){
			/**
			 * 属性
			 */
			//清除所有
			if (! $this->mProduct->removeProperty(0,$tId)){
				$this->db->trans_rollback();
				$this->ajaxReturn(0,'清除失败,请重新保存');
			}
			
			$tProperty = array();
			foreach ($lable as $k=>$v){
				$lable[$k]['product_id'] = $tId;
				$lable[$k]['sort'] = $k+1;
				$lable[$k]['value'] = str_replace(',', '|', $v['value']);
				
				//获取属性
				$temp = $lable[$k];
				$temp['value'] = explode(',', $v['value']);
				$tProperty[] = $temp;
				
			}
			
			$query = $this->mProduct->saveProperty($lable,0,true);
			if (! $query){
				$this->db->trans_rollback();
				$this->ajaxReturn(0,'保存失败');
			}
			
			/**
			 * 组合变体
			 * @var Ambiguous $variant
			 */
			$variant = $this->mProduct->setPropertyVariant($tProperty);
			
			if (! $this->mProduct->removePropertyVariant(0,$tId)){
				$this->db->trans_rollback();
				$this->ajaxReturn(0,'清除变体失败');
			}
			
			$tVariant = array();//变体数组
			foreach ($variant as $k=>$v){
				$tVariant[] = array(
						'product_id'=>$tId,
						'property'=>json_encode($v,JSON_UNESCAPED_UNICODE),
						'price'=>$goods_price,
						'quantity'=>$quantity,
						'is_limited' => $is_limited,
						'sort'=>$k+1,
						'status'=>2,
						'sale_quantity'=>0,
				);
			}
			
			$query = $this->mProduct->savePropertyVariant($tVariant,0,0,true);
			if (! $query){
				$this->db->trans_rollback();
				$this->ajaxReturn(0,'变体保存失败');
			}
		}

		/**
		 * 属性
		 */
		if ( ! empty($tag[0]['tag'])){
			//清除所有
			if (! $this->mProduct->removeTags(0,$tId)){
				$this->db->trans_rollback();
				$this->ajaxReturn(0,'清除失败,请重新保存');
			}
            $tagData = array();
			foreach ($tag as $k=>$v){
                $tagData[$k]['product_id'] = $tId;
                $tagData[$k]['sort'] = $k+1;
                $tagData[$k]['tag_name'] = $v['tag'];
                $tagData[$k]['tag_value'] = json_encode(explode(',', $v['value']), JSON_UNESCAPED_UNICODE);
			}
            unset($tag);
			$query = $this->mProduct->saveTags($tagData,true);
			if (! $query){
				$this->db->trans_rollback();
				$this->ajaxReturn(0,'保存失败');
			}
		}
		
		/**
		 * 产品详情
		 */
		
		//编辑
		if ($id){
			
			/**
			 * 编辑时删除图片
			 */
			if ( ! $imgs){
				$imgs = array();
			}
			//获取详情
			$tDe = $this->mProduct->getDetailList($tId,2);//获取图片
			foreach ($tDe as $k=>$v){
				if ( ! array_key_exists($v['sort'], $imgs)){
					$tDPath = strstr($v['content'],'?',true);
					if (file_exists($tDPath)){
						unlink($tDPath);//删除图片
					}
				}
			}
			
			/**
			 * 删除产品所有详情
			 */
			$query = $this->mProduct->removeDetail($tId);
			if ( ! $query){
				$this->ajaxReturn(0,'删除图片失败');
			}
		}

		//////详情////////////
        //处理文字
		if ($detail) {

            $tDetail = array();
            foreach ($detail as $k => $v) {
                $tDetail[$k] = array(
                    'product_id' => $tId,
                    'type' => 1,
                    'content' => $v,
                    'sort' => $k,
                );
            }
        }
			
        //处理图片[编辑]
        if ($imgs){
            foreach ($imgs as $k=>$v){
                $tDetail[$k] = array(
                        'product_id'=>$tId,
                        'type'=>2,
                        'content'=>$v,
                        'sort'=>$k,
                );
            }
        }
			
        if (!empty($_FILES)) {
            /**
             * 上传图片 新图片
             */
            $path = 'uploads/product/home/' . $tId . '/detail';
            $tImage = array();

            foreach ($_FILES as $k => $v) {
                if (strpos($k, '_detail') === false) {
                    continue;
                }

                $image = imageUpload($path, $k);
                if (!$image['status']) {
                    $this->db->trans_rollback();
                    foreach ($tImage as $kk => $vv) {
                        if (file_exists($vv)) {
                            unlink($vv);
                        }
                    }
                    $this->ajaxReturn(0, '详情图片上传失败');
                }

                $tImage = $image['data'];//存入临时变量。一旦有错误，全部删除

                //获取sort 存入详情数组
                $dk = (int)(strstr($k, '_detail', true));
                $tDetail[$dk] = array(
                    'product_id' => $tId,
                    'type' => 2,
                    'content' => $image['data'],
                    'sort' => $dk,

                );
            }
        }
        if (!empty($tDetail)) {
            ksort($tDetail);//排序

            //批量保存商品详情图片
            $query = $this->mProduct->saveDetail($tDetail, 0, 0, true);
            if (!$query) {
                $this->db->trans_rollback();
                foreach ($tImage as $kk => $vv) {
                    if (file_exists($vv)) {
                        unlink($vv);
                    }
                }
                $this->ajaxReturn(0, '保存失败');
            }

        }

		/**
		 *  移动新文件  轮播图
		 */
		if ($images){
			$imgPath = array();
			$path = 'uploads/product/home/'.$tId.'/';
			
			foreach ($images as $k=>$v){
				if (stripos($v,'temp') !== FALSE){
                    $size = getimagesize($v);
					$imgPath[] = saveTempImg($v,$path,true, $size[0], $size[1]);
				}else {
					$imgPath[] = str_replace(base_url(), '', $v);
				}
			}
			
			
			if($id){
				$tA = $this->mProduct->getInfo($id);
				$tImages = $tA['img'];
				foreach ($tImages as $k=>$v){
					if( ! in_array($v, $imgPath)){
						$v = strstr($v, '?',true);
						$tA = explode('/', $v);
						$filename = $tA[count($tA)-1];
						if (file_exists($v)){
							unlink($v);
						}
						if (file_exists($path.'sm/'.$filename)){
							@unlink($path.'sm/'.$filename);
						}
						if (file_exists($path.'xs/'.$filename)){
							@unlink($path.'xs/'.$filename);
						}
					}
				}
			}
            $imgPath = array_slice($imgPath, 0, 3);
			//保存
			$query = $this->mProduct->save(array('img'=>json_encode($imgPath)), $tId);
			if( ! $query){
				$this->db->trans_rollback();
				$this->ajaxReturn(0, '保存失败');
			}
		}
		
		if ( $icon){
			//上传封面图
			$path = 'uploads/product/home/'.$tId;

            $tA = saveCSVimg(array($icon), $path, 'icon');

            if( ! $tA){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '封面图上传失败');
            }

            $query = $this->mProduct->save(array('icon'=>$tA[0]), $tId);
            if( ! $query){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
		}
		
		$this->db->trans_commit();
        $getUrl = trim(post('back_url'));
		if ($getUrl){
            $backUrl = $getUrl;
        }else{
            $backUrl = getUrl('product/home');
        }
		$this->ajaxReturn(1,'保存成功','', $backUrl);
	}
	
	/**
	 * 获取列表
     * @author heyu
	 */
	public function getList(){
        $merchantId = $this->mMerchant->getInfoByCounty($this->countyItem);
        if (empty($merchantId)) $merchantId = array(0);

		$data = $this->mProduct->adminGetList($merchantId);

		//获取上级分类
		$m_ids = array();
		if ($data['data']){
			foreach ($data['data'] as $k=>$v){
				if ( ! in_array($v['merchant_id'], $m_ids)){
					$m_ids[] = $v['merchant_id'];
				}
			}
			
			if ($m_ids){
				$tMerchant = $this->mMerchant->getInfoByIds($m_ids);
			}
		}
		
		foreach ($data['data'] as $k=>$v){
			$data['aaData'][$k][] = '<img width="80%" src="'.getImage($v['icon'],'xs').'" class="" />';
			$data['aaData'][$k][] = isset($tMerchant[$v['merchant_id']]) ? $tMerchant[$v['merchant_id']]['shop_name'] : '暂无';
			$data['aaData'][$k][] = $v['name'];
			$data['aaData'][$k][] = $v['cat_name'];
			$data['aaData'][$k][] = $v['goods_price'];
			$data['aaData'][$k][] = $v['sale_quantity'];
			$data['aaData'][$k][] = $v['quantity'];
			$data['aaData'][$k][] = date('Y-m-d H:i:s',$v['addtime']);
            if($v['status'] > 0){
                $status = $v['status'] == 1 ? 2 : 1;
                $data['aaData'][$k][] = "<a href='".getUrl('product/home/changeStatus?id='.$v['id']).
                    "' class='ajax-request-btn deco' alert-message='是否确认".$this->mProduct->getStatus($status).
                    " “ ".$v['name']." ” ?'>".$this->mProduct->getStatus($v['status'],true)."</a>";
            }else{
                $data['aaData'][$k][] = $this->mProduct->getStatus($v['status'],true);
            }
			$btnConfig = adminCreateBtn(array(
							'label' => '详情',
							'attr' => array(
									'href' => getUrl('product/home/details?id='.$v['id']),
									'class' => 'btn btn-xs green-stripe default'
							),
							'tag' => 'a'
					));
            $btnConfig .= ' '.adminCreateBtn(array(
							'label' => '编辑',
							'attr' => array(
									'href' => getUrl('product/home/edit?id='.$v['id']),
									'class' => 'btn btn-xs blue-stripe default edit-btn'
							),
							'tag' => 'a'
					));
            if ($v['status'] == 0 || $v['status'] == 1){
                $btnConfig .= ' '.adminCreateBtn(array(
                    'label' => '删除',
                    'attr' => array(
                        'href' => getUrl('product/home/deleteProduct?id='.$v['id']),
                        'class' => 'btn btn-xs red-stripe default ajax-request-btn',
                        'alert-message' => '是否确定刪除 “ '.$v['name'].' ” ?'
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'product',
                        'key' => 'home-delete'
                    )
                ));
            }
			$data['aaData'][$k][] = $btnConfig;
		}
		
		unset($data['data']);
		echo json_encode($data);
	}

    /**
     * 删除商品
     * @author heyu
     */
    public function deleteProduct(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mProduct->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '商品不存在或已删除');
        }
        if ($info['status'] == -1){
            $this->ajaxReturn(0, '商品已删除');
        }
        if ($info['status'] == 2){
            $this->ajaxReturn(0, '商品已上架，不能删除');
        }
        if ($info['status'] == 0){
            $tA = $this->mProduct->deleteProduct($id);
            if (!$tA){
                $this->ajaxReturn(0, '删除失败');
            }
        }else if($info['status'] == 1){
            $tA = $this->mProduct->save(array('status' => -1), $id);
            if (!$tA){
                $this->ajaxReturn(0, '删除失败');
            }
        }else{
            $this->ajaxReturn(0, '数据有误');
        }
        $this->ajaxReturn(1, '保存成功','product');
    }

    /**
     * 修改上下架
     * @author heyu
     */
    public function changeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mProduct->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '商品不存在');
        }
        if ($info['status'] != 1 && $info['status'] != 2){
            $this->ajaxReturn(0, '商品不能上下架');
        }
        $status = $info['status'] == 1 ? 2 : 1;
        $tA = $this->mProduct->save(array('status' => $status), $id);
        if (!$tA){
            $this->ajaxReturn(0, '保存失败');
        }
        $this->ajaxReturn(1, '保存成功', 'product');
    }

	//////////////////////////////////////////////////////////////////
	//+--------------------------------------------------------------
	//|	商品属性
	//+--------------------------------------------------------------
	/**
	 * 添加属性标签
	 */
	public function saveProperty(){
		//表单验证
		$vConf = array(
				array('product_id', '产品id', 'required|is_natural_no_zero'),
				array('lable', '标签名称', 'required'),
				array('value', '标签属性', 'required'),
		);
		$this->formDataValidation($vConf);
		
		$productId = (int)post('product_id');
		$lable =trim(post('lable'));
		$value = explode(',',trim(post('value')));
		$tProduct = $this->mProduct->getInfo($productId);
		
		if ( ! $tProduct ){
			$this->ajaxReturn(0,'商品不存在');
		}
		
		if ( ! $value ){
			$this->ajaxReturn(0,'标签属性不对');
		}
		//获取该商品当前标签数量
		$sort = $this->mProduct->getTotalProperty($productId);
		
		$data = array(
				'product_id' => $productId,
				'lable'=>$lable,
				'value'=>implode('|', $value),
				'sort'=>$sort + 1,
		);
		
		if ( ! $tId = $this->mProduct->saveProperty($data)){
			$this->ajaxReturn(0,'新增失败');
		}
		
		$data['value'] = explode('|', $data['value']);
		$data['id'] = $tId;
		$this->ajaxReturn(1,'新增成功',$data);
	}
	
	/**
	 * 删除属性
	 */
	public function rmProperty(){
		$id = (int)get('id');
		if ( ! $id){
			$this->ajaxReturn(0,'属性id不存在');
		}
		
		$tProperty = $this->mProduct->getPropertyInfo($id);
		if ( ! $tProperty){
			$this->ajaxReturn(0,'该属性标签不存在');
		}
		
		if ( ! $this->mProduct->removeProperty($id)){
			$this->ajaxReturn(0,'删除失败');
		}
		
		$this->ajaxReturn(1,'删除成功',array('id'=>$id));
	}
	
	
	//////////////////////////////////////////////////////////////////
	//+--------------------------------------------------------------
	//|	商品评论
	//+--------------------------------------------------------------
	
	/**
	 * 获取列表
	 */
	public function getCommentList(){
        $iSortCol_0 = (int)get('iSortCol_0');
        if ($iSortCol_0 > 0){
            $_GET['iSortCol_0'] = $iSortCol_0 + 2;
        }
        $productId= get('product_id');
		$data = $this->mComment->adminGetList(0, $productId, $this->countyItem);
		foreach ($data['data'] as $k=>$v){
            $data['aaData'][$k][] = '<textarea readonly class="form-control remaks-item content textarea_height" style="height: 36px;">'.$v['content'].'</textarea>';
            $data['aaData'][$k][] = $v['score'];
            $data['aaData'][$k][] = $v['c_name'];
            // 商家回复
            if (!empty($v['reply'])){
                $data['aaData'][$k][] = '<a href="#" class="popovers" data-placement="left" data-trigger="hover" data-content="'
                    .$v['reply'].'" data-original-title="商家回复">[商家回复]</a>';
            }else{
                $data['aaData'][$k][] = '';
            }
            // 平台回复
            if (!empty($v['admin_reply'])){
                $data['aaData'][$k][] = '<a href="#" class="popovers" data-placement="left" data-trigger="hover" data-content="'
                    .$v['admin_reply'].'" data-original-title="平台回复">[平台回复]</a>';
            }else{
                $data['aaData'][$k][] = '';
            }

            $data['aaData'][$k][] = date('Y-m-d H:i:s',$v['addtime']);
            $btnConfig = adminCreateBtn(array(
                'label' => '图片',
                'attr' => array(
                    'href' => 'javascript:;',
                    'class' => 'btn btn-xs green-stripe default img-btn',
                    'data-id' => $v['id'],
                ),
                'tag' => 'a'
            ));
            if (empty($v['admin_reply'])){
                $btnConfig .=' '.adminCreateBtn(array(
                        'label' => '回复',
                        'attr' => array(
                            'href' => 'javascript:void(0)',
                            'class' => 'reply btn btn-xs blue-stripe default',
                            'data-id'=>$v['id'],
                        ),
                        'tag' => 'a'
                    ));
            }
            $btnConfig .=' '.adminCreateBtn(array(
                    'label' => '删除',
                    'attr' => array(
                        'href' => getUrl('product/comment/rmComment?id='.$v['id']),
                        'class' => 'btn btn-xs red-stripe default ajax-request-btn',
                        'alert-message'=>'确定要删除 “ '.$v['c_name'].' ” 的评价?',
                    ),
                    'tag' => 'a'
                ));
            $data['aaData'][$k][] = $btnConfig;
		}
		
		unset($data['data']);
		echo json_encode($data);
	}
	
	//////////////////////////////////////////////////////////////////
	//+--------------------------------------------------------------
	//|	商品规格
	//+--------------------------------------------------------------
	
	/**
	 * 添加属性标签
	 */
	public function saveVariant(){
		//表单验证
		$vConf = array(
				array('product_id', '产品id', 'required|is_natural_no_zero'),
				array('sort', '序号', 'required|is_natural_no_zero'),
				array('price', '价格', 'required'),
				array('is_limited', '库存状态', 'required|in_list[1,2]'),
		);
		$is_limited = (int)post('is_limited');
		if ($is_limited == 1){
            $vConf[] = array('quantity', '库存', 'required|is_natural_no_zero');
        }
		$this->formDataValidation($vConf);
		
		$productId 	= (int)post('product_id');
		$sort 		= trim(post('sort'));
		$price		= trim(post('price'));
		$quantity	= trim(post('quantity'));
		
		$tProduct = $this->mProduct->getInfo($productId);
		if ( ! $tProduct ){
			$this->ajaxReturn(0,'商品不存在');
		}
		
		$data = array(
		    'is_limited' => $is_limited,
            'price' => $price,
            'quantity'=>$is_limited == 1 ? $quantity : 999,
		);
		
		if ( ! $tId = $this->mProduct->savePropertyVariant($data,$productId,$sort)){
			$this->ajaxReturn(0,'保存失败');
		}
		
		$this->ajaxReturn(1,'保存成功');
	}
	
	/**
	 * 获取规格信息
	 */
	public function getVariant(){
		$productId = get('product_id');
		$sort = get('sort');
		
		$tA = $this->mProduct->getPropertyVariantInfo($productId,$sort);
		$tA['property'] = implode(',',json_decode($tA['property'],true));
		echo json_encode($tA);
	}
	
	/**
	 * 改变规格状态
	 */
	public function rmVariant(){
		$productId = get('product_id');
		$sort = get('sort');
		$status = get('status');
		
		if ( ! $this->mProduct->savePropertyVariant(array('status'=>$status),$productId,$sort)){
			$this->ajaxReturn(0,'保存失败');
		}
		$this->ajaxReturn(1,'保存成功');
	}

	/**
	 * 获取列表
	 */
	public function getVariantList(){
		$productId = get('product_id');
		if (! $productId){
			show_404();
		}
		
		$data = $this->mProduct->adminGetVariantList($productId);
		
		foreach ($data['data'] as $k=>$v){
			$title = implode(',',json_decode($v['property'],true));
			$data['aaData'][$k][] = $title;
			$data['aaData'][$k][] = $v['price'];
			$data['aaData'][$k][] = $v['is_limited'] == 1 ? '有限库存' : '无限库存';
			$data['aaData'][$k][] = $v['is_limited'] == 1 ? $v['quantity'] : 999;
			$data['aaData'][$k][] = $v['sale_quantity'];
            $status = $v['status'] == 1 ? 2 : 1;
			$data['aaData'][$k][] = "<a href='".getUrl('product/home/rmVariant?product_id='.$productId.'&sort='.$v['sort'].'&status='.$status).
                "' class='ajax-request-btn deco' alert-message='确定要将 “".$title." ”状态更改为".$this->adminStatus($status).
                "?'>".$this->adminStatus($v['status'],true)."</a>";
			$data['aaData'][$k][] = adminCreateBtn(
                array(
                    'label' => '编辑',
                    'attr' => array(
                        'href' => getUrl('product/home/getVariant?product_id='.$productId.'&sort='.$v['sort']),
                        'class' => 'btn btn-xs blue-stripe default variant_edit'
                    ),
                    'tag' => 'a'
                ));
		}
		
		unset($data['data']);
		echo json_encode($data);
	}

}
